package com.aifast.dict.core;

import cn.hutool.core.util.ObjectUtil;
import com.aifast.dict.annotations.DictBind;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import java.io.IOException;

/**
 * @Author AiFast
 * @since 2022/12/28 14:53
 */
public class FastDictSerializer extends JsonSerializer<Object> implements ContextualSerializer {

    @Value("${ai.dict.enable}")
    private boolean enable;
    private DictBind dictBind;

    public FastDictSerializer(){}

    public FastDictSerializer(DictBind db){
        this.dictBind = db;
    }

    @Autowired
    private FastDictTranslator translator;


    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeObject(value);
        if(enable){
            gen.writeFieldName(translator.genTargetFieldName(gen.getOutputContext().getCurrentName(),this.dictBind.target()));
            gen.writeObject(translator.genTargetFieldValue(this.dictBind,value));
        }

    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        DictBind annotation = property.getAnnotation(DictBind.class);
        if(ObjectUtil.isNotNull(annotation)){
            this.dictBind = annotation;
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}
